package xijia.plus.docs.thymeleafuser.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import io.github.wslxm.springbootplus2.core.config.error.ErrorException;
import io.github.wslxm.springbootplus2.core.utils.date.LocalDateTimeUtil;
import io.github.wslxm.springbootplus2.manage.sys.service.BannerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import xijia.plus.docs.manage.all.model.vo.DocInfoVO;
import xijia.plus.docs.manage.all.model.vo.DocMenuVO;
import xijia.plus.docs.manage.all.service.DocInfoService;
import xijia.plus.docs.thymeleafuser.constant.PageEnum;
import xijia.plus.docs.thymeleafuser.constant.TpParamsKey;
import xijia.plus.docs.thymeleafuser.service.PageService;
import xijia.plus.docs.thymeleafuser.util.IpUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.regex.Matcher;

/**
 * 逻辑层，页面渲染数据获取处理
 *
 * @author wangsong
 * @version 1.0.0
 * @mail 1720696548@qq.com
 * @date 2022/10/20 0020 14:55
 */
@Service
@Slf4j
public class PageServiceImpl extends BaseServiceImpl implements PageService {

    @Autowired
    private BannerService bannerApi;
    @Autowired
    private DocInfoService docInfoApi;
    @Autowired
    private HttpServletRequest request;

    @Override
    public String home(Model model) {
        List<DocMenuVO> trees = super.getTree();
        model.addAttribute(TpParamsKey.STATIC_PATH, "");
        model.addAttribute(TpParamsKey.PAGE, "index");
        model.addAttribute(TpParamsKey.ADDR_ID, IpUtil.getIpAddr(request));
        model.addAttribute(TpParamsKey.BASE_URL, request.getRequestURL().toString().replace(request.getServletPath(), ""));
        model.addAttribute(TpParamsKey.MENU_TOP, trees.get(0).getChildren());
        model.addAttribute(TpParamsKey.DOCS_TREE, JSON.parse(JSON.toJSONString(super.getDocTree())));
        model.addAttribute(TpParamsKey.SEO, super.getConfig("seo-home"));
        model.addAttribute(TpParamsKey.CONFIG, JSON.parseObject(super.getConfig("doc-config")));
        return PageEnum.INDEX.getPage();
    }


    @Override
    public String findByName(Model model, String categoryName, String name) {
        List<DocMenuVO> trees = super.getTree();
        model.addAttribute(TpParamsKey.STATIC_PATH, "");
        model.addAttribute(TpParamsKey.ADDR_ID, IpUtil.getIpAddr(request));
        model.addAttribute(TpParamsKey.BASE_URL, request.getRequestURL().toString().replace(request.getServletPath(), ""));
        model.addAttribute(TpParamsKey.MENU_TOP, trees.get(0).getChildren());
        model.addAttribute(TpParamsKey.DOCS_TREE, JSON.parse(JSON.toJSONString(super.getDocTree())));
        model.addAttribute(TpParamsKey.CONFIG, JSON.parseObject(super.getConfig("doc-config")));

        // 查询文档
        DocInfoVO docInfoVO = null;
        try {
             docInfoVO = docInfoApi.findByName(super.getTenantName(), categoryName, name);
        }catch (ErrorException e){
            return PageEnum.FORWARD_ERROR_404.getPage();
        }catch (Exception e){
            return PageEnum.FORWARD_ERROR_500.getPage();
        }

//        if (!resDocInfoVO.getCode().equals(HttpStatus.HTTP_OK)) {
//            return PageEnum.REDIRECT_ERROR_404.getPage();
//        }
        // 处理内容中的 {{}}
        docInfoVO.setUpdateTimeStr(LocalDateTimeUtil.parse(docInfoVO.getUpdateTime()));
        if (StringUtils.isNotBlank(docInfoVO.getContentHtml())) {
            for (int i = 0; i < 2; i++) {
                docInfoVO.setContentHtml(docInfoVO.getContentHtml().replaceAll("\\{\\{", "\\{ \\{"));
                docInfoVO.setContentHtml(docInfoVO.getContentHtml().replaceAll("}}", "} }"));
            }
        }
        model.addAttribute(TpParamsKey.DOC_INFO, docInfoVO);
        model.addAttribute(TpParamsKey.SEO, this.getSeoStr(docInfoVO, super.getConfig("seo-doc")));
        return PageEnum.DOC.getPage();
    }


    /**
     * 获取seo 数据
     *
     * @author wangsong
     * @mail 1720696548@qq.com
     * @date 2022/10/28 0028 16:08
     * @version 1.0.0
     */
    @Override
    public String getSeoStr(DocInfoVO docInfoVO, String seoDocConfig) {
        String seo = seoDocConfig;
        // seo 关键三要素
        seo = seo.replaceAll("\\$\\{seoTitle}", ObjectUtil.defaultIfBlank(docInfoVO.getSeoTitle(), docInfoVO.getName()));
        seo = seo.replaceAll("\\$\\{seoDescription}", StringUtils.isNotBlank(docInfoVO.getSeoDescription()) ? docInfoVO.getSeoDescription() : this.getStripHtml(docInfoVO.getContentHtml()));
        seo = seo.replaceAll("\\$\\{seoKeywords}", ObjectUtil.defaultIfBlank(docInfoVO.getSeoKeyword(), docInfoVO.getTypeName()));
        // 文档数据
        seo = seo.replaceAll("\\$\\{name}", ObjectUtil.defaultIfBlank(docInfoVO.getName(), ""));
        seo = seo.replaceAll("\\$\\{author}", ObjectUtil.defaultIfBlank(docInfoVO.getAuthor(), ""));
        seo = seo.replaceAll("\\$\\{createTime}", ObjectUtil.defaultIfBlank(LocalDateTimeUtil.parse(docInfoVO.getCreateTime()), ""));
        seo = seo.replaceAll("\\$\\{updateTime}", ObjectUtil.defaultIfBlank(LocalDateTimeUtil.parse(docInfoVO.getUpdateTime()), ""));
        seo = seo.replaceAll("\\$\\{typeName}", ObjectUtil.defaultIfBlank(docInfoVO.getTypeName(), ""));
        return seo;
    }


    /**
     * 获取 内容前200 字
     * <p>
     * 如果不到200 获取全部
     *
     * @author wangsong
     * @email 1720696548@qq.com
     * @date 2022/12/24 0024 11:18
     * @version 1.0.0
     */
    public String getStripHtml(String content) {
        if (StringUtils.isBlank(content)) {
            return "";
        }
        // <p>段落替换为换行
        //content = content.replaceAll("<p .*?>", " ");
        // <br><br/>替换为换行
        // content = content.replaceAll("<br\\s*/?>", " ");
        // 去掉其它的<>之间的东西
        content = content.replaceAll("\\<.*?>", " ");
        content = content.replaceAll("\n", " ");
        content = content.replaceAll("\r", " ");
        // 防止替换后的内容中出现 $
        content = Matcher.quoteReplacement(content);
        // 还原HTML
        // content = HTMLDecoder.decode(content);
        if (content.length() > 200) {
            return content.substring(0, 200);
        }
        return content;
    }

}
